import router from "../router";
import axios from "axios";
import {getWebConfigFromLocal} from "../utils/toml"
import { getTempValue } from "../utils/temp"
import get from "lodash/get"
//
import NProgress from "nprogress";
import "nprogress/nprogress.css";
// import {useStore} from "vuex"
// //
import {
  nprogressConfig,
  defaultConfig,
} from "./config";
// 防抖
import { AxiosAnti } from "./Anti";
//
import { tipError } from "../utils/tip";
// import { saveLocal, getLocal } from "@/utils/storage";
//
// nprogress 配置
NProgress.configure(nprogressConfig);
// @ts-ignore
axios.defaults.baseURL = $location.origin;
const http = axios.create(defaultConfig);
//
const axiosAnti = new AxiosAnti(axios);
// 拦截 request 请求
http.interceptors.request.use((config) => {
  // 开启 ngprogress
  NProgress.start();
  //
  axiosAnti.init(config);
  //
  const cfg = getWebConfigFromLocal() || {}
  const {axios = {headers:{},auth:{}}} = cfg;
  // 添加自定义请求头
  config.headers = {...axios.headers,...(config.headers || {})};
  //
  const auth = axios.auth;
  const authKey = auth.key || "Sunny-Auth";
  const authVal = auth.value || "Bearer {{token}}"
  // @ts-ignore
  if (config.headers[authKey] !== false) {
    // @ts-ignore
    config.headers[authKey] = getTempValue(authVal);
  }
  return config;
});

// 拦截 response
http.interceptors.response.use(
  (resp) => {
    // 关闭 ngprogress
    NProgress.done();
    //
    axiosAnti.finish(resp.config)
    // 解析接口状态 返回为 true 则正常返回 数据 若为 false 则返回 异常
    // 拦截规则
    return resp;
  },
  (error) => {
    // 关闭 ngprogress
    NProgress.done();
    //
    if(axiosAnti.error(error)){
      return undefined;
    }
    const cfg = getWebConfigFromLocal() || {}
    const {axios = {}} = cfg;
    const {errorStatus = {},errorMsg = {enabled:true}} = axios
    const resp = error.response;
    const status = resp?.status;
    //
    const path = get(errorStatus,String(status));
    if(path){
      router.push(path)
    }
    const isTip = errorMsg.enabled && (path ? errorMsg.tipStatus && errorMsg.tipStatus.includes(status) : true)
    if(isTip){
      const msg:string = errorMsg.msg ? getTempValue(errorMsg.msg,error) : resp?.statusText;
      msg && tipError(msg)
    }

    return Promise.reject(error);
  }
);

//

export default http;
